package com.atguigu.gmall.order.consumer;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.mapper.OrderDetailMapper;
import com.atguigu.gmall.order.mapper.OrderInfoMapper;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.pay.feign.PayFeign;
import com.atguigu.gmall.product.feign.ProductFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 订单的取消监听类
 */
@Log4j2
@Component
public class OrderCancelConsumer {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayFeign payFeign;

    /**
     * 取消订单的消息消费者
     * @param msg
     */
    @RabbitListener(queues = "normal_queue")
    public void cancelOrder(String msg, Channel channel, Message message){
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //获取订单号
        long orderId = Long.parseLong(msg);
        //关闭交易
        Boolean aBoolean = payFeign.closePay(orderId);
        if (aBoolean){
            //取消订单
            orderService.cancelOrder(orderId);
        }
        //否则，将消息丢回队列，重新再试一次
        try {
            channel.basicReject(deliveryTag,true);
            //两次以后,还是失败,记录到数据库中区,同时取消此笔订单的关闭和回滚
            if (messageProperties.getRedelivered()){
                //将消息进行记录--日志--数据库
                log.info(JSONObject.toJSONString(message));
                //拒绝消息
                channel.basicReject(deliveryTag,false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
